package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.sun.javafx.collections.MappingChange;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        //判断用户名和密码是否为空
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户
        LambdaQueryWrapper<AdUser> query = new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,dto.getName());
        AdUser one = this.getOne(query);
        //用户名不存在,提示
        if (one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //用户存在,获取用户表中的盐
        String salt = one.getSalt();
        //使用户传入的密码加盐在进行MD5加密
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        //得到的密码和数据库表中的密码进行对比
        if (!password.equals(one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致,使用工具生成token返回给前端
        Map<String,Object> map = new HashMap<>();
        map.put("userId",one.getId());
        map.put("userName",one.getName());
        String token = AppJwtUtil.getToken(map);

        Map<String,Object> resultMap = new HashMap<>();
        //过滤敏感信息
        one.setPassword(null);
        one.setSalt(null);
        one.setPhone(null);
        resultMap.put("user",one);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
